<?php

use App\Exceptions\JsonResponseException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: [
            __DIR__.'/../routes/api.php',
            __DIR__.'/../routes/adminapi.php'
        ],
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'set.team.id' => App\Http\Middleware\SetTeamIdMiddleware::class, // 设置会员组team_id 前端个人1企业2，后台9
            'role' => Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission' => Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (Throwable $e, Request $request)  {
            if($request->is('api/*') || str_starts_with($request->headers->get('Content-Type'), 'application/json')) {
                $env = config('app.env');

                match (true) {
                    $e instanceof AuthenticationException => throw new JsonResponseException($e->getMessage(), [], 401),
                    $e instanceof UnauthorizedException => throw new JsonResponseException($e->getMessage(), [], 403),
                    $e instanceof MethodNotAllowedHttpException => throw new JsonResponseException(
                        'local' === $env ? $e->getMessage() : '请求的资源不存在或已被删除。',
                        [],
                        404
                    ),
                    $e instanceof NotFoundHttpException => throw new JsonResponseException(
                        'local' === $env ? $e->getMessage() : '请求的资源不存在或已被删除。',
                        [],
                        404
                    ),
                    $e instanceof InvalidArgumentException => throw new JsonResponseException(
                        'local' === $env ? $e->getMessage() : '传递的参数无效，请检查请求数据。',
                        [],
                        400
                    ),
                    default => throw new JsonResponseException(
                        'local' === $env ? $e->getMessage() : '系统发生未知错误，请稍后再试或联系技术支持。'
                    ),
                };
            }
        });
    })->create();
